Ext.define('CDR.controller.manager.PBX', {
	extend : 'Ext.app.Controller',
	selectedFactory : null,
	pbxViewFormType: null,
	currentPBXViewItem: null,
	views : ['manager.pbx.PBXFactory', 'manager.pbx.PBXView',
			'manager.pbx.PBXViewContainer', 'manager.pbx.PBXViewForm' ,
			'manager.pbx.PBXProfileView'],
	stores : [ 'manager.pbx.PBXViewStore', 'manager.pbx.PBXViewFormStore',
			 'manager.pbx.PBXProfileListStore'],
	models : [ 'manager.pbx.PBXViewModel', 'manager.pbx.PBXViewFormModel'],

	refs: [{
        ref: 'pbxPactory',
        selector: 'pbxfactory'
    }],
    statics: {
    	PBX_VIEW_FORM_NEW_URL: 'create-pbx',
    	PBX_VIEW_FORM_EDIT_URL: 'edit-pbx'
    },
	init : function() {
		this.control({
			'pbxfactory' : {
				render : this.initPBXFactory,
				expand : this.replaceView
			},
			'pbxfactory > button' : {
				click : this.reloadPBXView
			},
			'pbxview' : {
				itemdblclick: this.editPBXViewItem,
				itemcontextmenu: this.showContextMenuItem
			},
			'#menu-item-add-profile' : {
				click: this.addProfileToPBXViewItem
			},
			'pbxviewcontainer button[action=new-pbx]' : {
				click: this.addPBXViewItem
			},
			'pbxviewform button[action=save]' : {
				click: this.submitPBXViewForm
			},
			'pbxviewcontainer textfield[action=filter]' : {
				change: this.filterPBXViewItem
			}
		});

	},
	/**
	 * get list pbx factory
	 * 
	 * @param me
	 * @param opts
	 */
	initPBXFactory : function(me, opts) {
		Ext.Ajax.request({
			scope : this,
			url : 'list-pbx-factory',
			success : function(response, opts) {
				var obj = Ext.decode(response.responseText);
				Ext.each(obj.results, function(item) {
					this.addItem(item.name, item.description, item.id);
				}, me);
			}
		});
	},
	/**
	 * reload list pbx of pbxfactory in right view
	 * 
	 * @param me
	 * @param e
	 * @param opts
	 */
	reloadPBXView : function(me, e, opts) {
		this.selectedFactory = me;
		var pbxView = Ext.getCmp('x-view-pbxviewcontainer-pbxview');
		if(pbxView){
			pbxView.store.load({params:{'pbxFactoryId': me.obId}});
		}
	},
	/**
	 * add pbxViewContaner to parent view
	 */
	replaceView : function() {
		var managerViewCenter = Ext.getCmp('x-view-managerview');
		var pbxViewContainer = Ext.getCmp('x-view-pbxviewcontainer');
		if (managerViewCenter && pbxViewContainer) {
			managerViewCenter.removeAll(false);
			managerViewCenter.add(pbxViewContainer);
		}
	},
	
	/**
	 * edit pbx view when dbclick
	 * @param me
	 * @param record
	 */
	editPBXViewItem: function(me, record){
		this.currentPBXViewItem = record;
		//set type for form
		this.pbxViewFormType = CDR.Constant.WINDOW_EDIT_MODE;
		var pbxViewForm = Ext.getCmp('x-view-pbxviewcontainer-pbxviewform');
		var pbxViewContainer = Ext.getCmp('x-view-pbxviewcontainer');
		if(pbxViewContainer && pbxViewForm) {
			pbxViewForm.getForm().reset();
			pbxViewForm.store.load({params:{'pbxId': record.data.obId}, callback: function(records, operation, success){
				if(success && records){
					pbxViewForm.loadRecord(records[0]);
					pbxViewContainer.replaceSouthView(pbxViewForm);
				}
			}});
		}
	},
	
	/**
	 * add new pbx view item to db
	 */
	addPBXViewItem: function(){
		if(this.selectedFactory == null || this.selectedFactory.obId == 0){
			Ext.Msg.alert('Failed', "Please seletect a factory");
			return;
		}
		this.pbxViewFormType = CDR.Constant.WINDOW_NEW_MODE;
		var pbxViewForm = Ext.getCmp('x-view-pbxviewcontainer-pbxviewform');
		var pbxViewContainer = Ext.getCmp('x-view-pbxviewcontainer');
		if(pbxViewContainer && pbxViewForm) {
			pbxViewForm.getForm().reset();
			var record = Ext.create('CDR.model.manager.pbx.PBXViewFormModel');
			record.set({'factoryId': this.selectedFactory.obId});
			pbxViewForm.loadRecord(record);
			pbxViewContainer.replaceSouthView(pbxViewForm);
		}
	},
	/**
	 * submit pbx view form
	 */
	submitPBXViewForm: function() {
		var form = Ext.getCmp('x-view-pbxviewcontainer-pbxviewform').getForm();
		if(this.pbxViewFormType === CDR.Constant.WINDOW_NEW_MODE) {
			if (form.isValid()) {
				form.submit({
					scope: this,
					url: CDR.controller.manager.PBX.PBX_VIEW_FORM_NEW_URL,
					success: function(form, action) {
					   Ext.Msg.alert('Success', action.result.msg);
					   var values = form.getValues();
					   var data = action.result;
					   //add item back to view pbx
					   var pbxView = Ext.getCmp('x-view-pbxviewcontainer-pbxview');
					   pbxView.store.add({name: values.name, obId: data.obId, thumb: data.thumb});
					},
					failure: function(form, action) {
						Ext.Msg.alert('Failed', action.result.msg);
					}
				});
			}
		} else if(this.pbxViewFormType === CDR.Constant.WINDOW_EDIT_MODE){
			if (form.isValid()) {
				form.submit({
					scope: this,
					url: CDR.controller.manager.PBX.PBX_VIEW_FORM_EDIT_URL,
					success: function(form, action) {
					   Ext.Msg.alert('Success', action.result.msg);
					   var values = form.getValues();
					   //update back to view item
					   this.currentPBXViewItem.set(values);
					},
					failure: function(form, action) {
						Ext.Msg.alert('Failed', action.result.msg);
					}
				});
			}
		}
	},
	/**
	 * filter item pbx view
	 */
	filterPBXViewItem: function(me, newVal, oldVal) {
		var pbxView = Ext.getCmp('x-view-pbxviewcontainer-pbxview');
		pbxView.store.clearFilter();
		pbxView.store.filter(new Ext.util.Filter({
				filterFn: function(item) {
					var searchtest,namematch;
					var escapere = Ext.String.escapeRegex;
					searchtest = new RegExp(escapere(newVal), 'i');
					namematch = searchtest.test(item.data.name);
					return namematch;
				}
			})
		);
	},
	/**
	 * show context menu for pbx view item
	 */
	showContextMenuItem: function(el, r, node, index, e, eOpts){
		e.stopEvent();
		el.select(r);
		el.menu.showAt(e.xy);
	},
	/**
	 * add and edit profile for a pbx item
	 */
	addProfileToPBXViewItem: function() {
		var pbxViewContainer = Ext.getCmp('x-view-pbxviewcontainer');
		var pbxView = Ext.getCmp('x-view-pbxviewcontainer-pbxview');
		var select = pbxView.getSelectionModel().getLastSelected();
		var profileListStore = this.getManagerPbxPBXProfileListStoreStore();
		profileListStore.load({
			params:{'pbxId': select.data.obId},
			callback: function(records, operation, success){
				if(success) {
					pbxViewContainer.addProfile(records, select);
				}
			}
		});
	}
	
});